package com.yeyuanqi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeyuanqi.dao.ArticleMapper;
import com.yeyuanqi.dao.CommentMapper;
import com.yeyuanqi.dao.StatisticMapper;
import com.yeyuanqi.model.domain.Article;
import com.yeyuanqi.model.domain.Comment;
import com.yeyuanqi.model.domain.CommentCount;
import com.yeyuanqi.model.domain.Statistic;
import com.yeyuanqi.service.ICommentService;
import com.yeyuanqi.vo.CountVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class CommentServiceImpl implements ICommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private StatisticMapper statisticMapper;
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public PageInfo<Comment> getComment(Integer aid, int page, int count) {
        PageHelper.startPage(page,count);
        List<Comment> commentList= commentMapper.selectCommentWithPage(aid);
        PageInfo<Comment> commentInfo = new PageInfo<>(commentList);
        return commentInfo;
    }

    @Override
    public void pushComment(Comment comment) {
        commentMapper.pushComment(comment);
        Statistic statistic = statisticMapper.selectStatisticWithArticleId(comment.getArticleId());
        statistic.setCommentsNum(statistic.getCommentsNum()+1);
        statisticMapper.updateArticleCommentsWithId(statistic);
    }

    @Override
    public PageInfo<Comment> getAllComment(int page, int count) {
        PageHelper.startPage(page,count);
        List<Comment> commentList = commentMapper.selectCommentAll();
        PageInfo<Comment> pageInfo = new PageInfo<>(commentList);
        return pageInfo;
    }

    @Override
    public void delCommentByAid(Integer articleId) {

        commentMapper.delCommentByAid(articleId);

    }

    @Override
    public void delCommentById(Integer Id) {

        commentMapper.delCommentById(Id);
    }

    @Override
    public CountVO selectCommentCount() {
        CountVO countVO = new CountVO();
        //先查出数据
        List<CommentCount> commentCounts = this.commentMapper.selectCommentCount();
        List<String> names = new ArrayList<>();
        List<Integer> values = new ArrayList<>();
        for (CommentCount commentCount : commentCounts) {
            Article article = articleMapper.selectArticleWithId(commentCount.getId());
            String name = article.getTitle();
//            name= "\"" + name +"\"";
            names.add(name);
            values.add(commentCount.getValuee());
        }
        countVO.setNames(names);
        countVO.setValues(values);
        return countVO;

    }
}
